// 数据引擎模块 - 负责数据流处理、聚合和管理

class DataEngine {
    constructor() {
        this.dataStores = {};
        this.maxDataPoints = realTimeSystem.config.maxDataPoints || 100;
        this.aggregationIntervals = {};
        this.listeners = {};
        this.performanceMonitor = {
            dataPointsProcessed: 0,
            aggregationTime: 0,
            lastResetTime: Date.now()
        };
    }

    // 初始化数据引擎
    init() {
        console.log('数据引擎初始化...');
        
        // 创建默认数据存储
        this.createDataStore('system');
        this.createDataStore('finance');
        this.createDataStore('iot');
        this.createDataStore('realtime');
        this.createDataStore('alerts');
        
        // 开始性能监控
        this.startPerformanceMonitoring();
        
        console.log('数据引擎初始化完成');
    }

    // 创建数据存储
    createDataStore(name, options = {}) {
        if (this.dataStores[name]) {
            console.warn(`数据存储 ${name} 已存在`);
            return this.dataStores[name];
        }
        
        const dataStore = {
            name,
            data: [],
            maxPoints: options.maxPoints || this.maxDataPoints,
            lastUpdated: null,
            metadata: {}
        };
        
        this.dataStores[name] = dataStore;
        console.log(`数据存储 ${name} 已创建`);
        
        return dataStore;
    }

    // 添加数据点
    addDataPoint(storeName, data) {
        const store = this.dataStores[storeName];
        if (!store) {
            console.error(`数据存储 ${storeName} 不存在`);
            return false;
        }
        
        const timestamp = data.timestamp || Date.now();
        const dataPoint = {
            ...data,
            timestamp
        };
        
        // 添加数据点
        store.data.push(dataPoint);
        store.lastUpdated = timestamp;
        
        // 限制数据点数量
        if (store.data.length > store.maxPoints) {
            store.data = store.data.slice(-store.maxPoints);
        }
        
        // 更新性能统计
        this.performanceMonitor.dataPointsProcessed++;
        
        // 触发数据更新事件
        this.emit(`${storeName}:updated`, dataPoint);
        
        return true;
    }

    // 批量添加数据点
    addDataPoints(storeName, dataPoints) {
        dataPoints.forEach(dataPoint => {
            this.addDataPoint(storeName, dataPoint);
        });
    }

    // 获取数据存储
    getDataStore(storeName) {
        return this.dataStores[storeName] || null;
    }

    // 获取数据
    getData(storeName, options = {}) {
        const store = this.dataStores[storeName];
        if (!store) {
            console.error(`数据存储 ${storeName} 不存在`);
            return [];
        }
        
        let data = [...store.data];
        
        // 应用时间范围过滤
        if (options.startTime && options.endTime) {
            data = data.filter(d => d.timestamp >= options.startTime && d.timestamp <= options.endTime);
        } else if (options.startTime) {
            data = data.filter(d => d.timestamp >= options.startTime);
        } else if (options.endTime) {
            data = data.filter(d => d.timestamp <= options.endTime);
        }
        
        // 应用限制
        if (options.limit && options.limit > 0) {
            data = data.slice(-options.limit);
        }
        
        return data;
    }

    // 配置数据聚合
    configureAggregation(storeName, options) {
        const store = this.dataStores[storeName];
        if (!store) {
            console.error(`数据存储 ${storeName} 不存在`);
            return false;
        }
        
        // 清除现有的聚合定时器
        if (this.aggregationIntervals[storeName]) {
            clearInterval(this.aggregationIntervals[storeName]);
        }
        
        // 创建新的聚合定时器
        this.aggregationIntervals[storeName] = setInterval(() => {
            this.aggregateData(storeName, options.method);
        }, options.interval);
        
        console.log(`数据聚合已配置: ${storeName}, 方法: ${options.method}, 间隔: ${options.interval}ms`);
        
        return true;
    }

    // 聚合数据
    aggregateData(storeName, method = 'average') {
        const store = this.dataStores[storeName];
        if (!store || store.data.length === 0) {
            return;
        }
        
        const startTime = performance.now();
        
        // 根据聚合方法处理数据
        let aggregatedData;
        
        switch (method) {
            case 'average':
                aggregatedData = this.calculateAverage(store.data);
                break;
            case 'sum':
                aggregatedData = this.calculateSum(store.data);
                break;
            case 'min':
                aggregatedData = this.findMin(store.data);
                break;
            case 'max':
                aggregatedData = this.findMax(store.data);
                break;
            case 'median':
                aggregatedData = this.calculateMedian(store.data);
                break;
            default:
                aggregatedData = this.calculateAverage(store.data);
        }
        
        const endTime = performance.now();
        this.performanceMonitor.aggregationTime += (endTime - startTime);
        
        // 触发聚合数据事件
        this.emit(`${storeName}:aggregated`, aggregatedData);
        
        return aggregatedData;
    }

    // 计算平均值
    calculateAverage(data) {
        if (!data || data.length === 0) return null;
        
        const result = { timestamp: Date.now() };
        const keys = Object.keys(data[0]).filter(k => k !== 'timestamp');
        
        keys.forEach(key => {
            const values = data.map(d => d[key]).filter(v => typeof v === 'number');
            if (values.length > 0) {
                result[key] = values.reduce((sum, val) => sum + val, 0) / values.length;
            }
        });
        
        return result;
    }

    // 计算总和
    calculateSum(data) {
        if (!data || data.length === 0) return null;
        
        const result = { timestamp: Date.now() };
        const keys = Object.keys(data[0]).filter(k => k !== 'timestamp');
        
        keys.forEach(key => {
            const values = data.map(d => d[key]).filter(v => typeof v === 'number');
            if (values.length > 0) {
                result[key] = values.reduce((sum, val) => sum + val, 0);
            }
        });
        
        return result;
    }

    // 查找最小值
    findMin(data) {
        if (!data || data.length === 0) return null;
        
        const result = { timestamp: Date.now() };
        const keys = Object.keys(data[0]).filter(k => k !== 'timestamp');
        
        keys.forEach(key => {
            const values = data.map(d => d[key]).filter(v => typeof v === 'number');
            if (values.length > 0) {
                result[key] = Math.min(...values);
            }
        });
        
        return result;
    }

    // 查找最大值
    findMax(data) {
        if (!data || data.length === 0) return null;
        
        const result = { timestamp: Date.now() };
        const keys = Object.keys(data[0]).filter(k => k !== 'timestamp');
        
        keys.forEach(key => {
            const values = data.map(d => d[key]).filter(v => typeof v === 'number');
            if (values.length > 0) {
                result[key] = Math.max(...values);
            }
        });
        
        return result;
    }

    // 计算中位数
    calculateMedian(data) {
        if (!data || data.length === 0) return null;
        
        const result = { timestamp: Date.now() };
        const keys = Object.keys(data[0]).filter(k => k !== 'timestamp');
        
        keys.forEach(key => {
            const values = data.map(d => d[key]).filter(v => typeof v === 'number').sort((a, b) => a - b);
            if (values.length > 0) {
                const mid = Math.floor(values.length / 2);
                result[key] = values.length % 2 === 0 ? 
                    (values[mid - 1] + values[mid]) / 2 : 
                    values[mid];
            }
        });
        
        return result;
    }

    // 数据采样
    sampleData(storeName, sampleSize) {
        const data = this.getData(storeName);
        if (data.length <= sampleSize) {
            return data;
        }
        
        const step = Math.floor(data.length / sampleSize);
        const sampledData = [];
        
        for (let i = 0; i < sampleSize; i++) {
            const index = Math.min(i * step, data.length - 1);
            sampledData.push(data[index]);
        }
        
        // 确保包含最后一个数据点
        if (sampledData[sampledData.length - 1] !== data[data.length - 1]) {
            sampledData[sampledData.length - 1] = data[data.length - 1];
        }
        
        return sampledData;
    }

    // 清空数据存储
    clearDataStore(storeName) {
        const store = this.dataStores[storeName];
        if (store) {
            store.data = [];
            store.lastUpdated = null;
            console.log(`数据存储 ${storeName} 已清空`);
            return true;
        }
        return false;
    }

    // 注册监听器
    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
        
        // 返回取消监听函数
        return () => {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        };
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 开始性能监控
    startPerformanceMonitoring() {
        setInterval(() => {
            const currentTime = Date.now();
            const elapsedTime = (currentTime - this.performanceMonitor.lastResetTime) / 1000;
            
            const performanceStats = {
                dataPointsPerSecond: Math.round(this.performanceMonitor.dataPointsProcessed / elapsedTime),
                avgAggregationTime: this.performanceMonitor.aggregationTime / this.performanceMonitor.dataPointsProcessed || 0,
                totalDataPoints: this.performanceMonitor.dataPointsProcessed,
                timestamp: currentTime
            };
            
            // 触发性能统计事件
            this.emit('performance:stats', performanceStats);
            
            // 重置计数器
            this.performanceMonitor.dataPointsProcessed = 0;
            this.performanceMonitor.aggregationTime = 0;
            this.performanceMonitor.lastResetTime = currentTime;
        }, 5000); // 每5秒统计一次
    }

    // 获取数据引擎状态
    getStatus() {
        const storeStats = {};
        Object.entries(this.dataStores).forEach(([name, store]) => {
            storeStats[name] = {
                dataPoints: store.data.length,
                maxPoints: store.maxPoints,
                lastUpdated: store.lastUpdated,
                hasAggregation: !!this.aggregationIntervals[name]
            };
        });
        
        return {
            stores: storeStats,
            performance: { ...this.performanceMonitor }
        };
    }

    // 停止数据引擎
    stop() {
        // 清除所有聚合定时器
        Object.values(this.aggregationIntervals).forEach(interval => {
            clearInterval(interval);
        });
        
        this.aggregationIntervals = {};
        console.log('数据引擎已停止');
    }
}

// 创建并注册数据引擎实例
const dataEngine = new DataEngine();
realTimeSystem.registerModule('dataStream', dataEngine);

// 导出数据引擎
window.dataEngine = dataEngine;